package com.qf.microgoods.goods.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.Favorite;
import com.qf.common.core.util.UserUtils;
import com.qf.microgoods.goods.mapper.FavoriteMapper;
import com.qf.microgoods.goods.param.FavoriteParam;
import com.qf.microgoods.goods.service.FavoriteService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 天--道--酬--勤
 *
 * @author LiangGaoQiang
 * @ClassName GrassFavoriteServiceImpl
 * @Date: 2025/6/1 18:05
 * @Description: 描述
 */
@Service
public class GrassFavoriteServiceImpl implements FavoriteService {

    @Resource
    private FavoriteMapper favoriteMapper;

    @Override
    public boolean addFavorite(FavoriteParam favoriteParam) {
        // 获取当前用户id
        Integer uid = UserUtils.getUid();


        // 先根据用户id和文章id查询是否已经收藏过
        Favorite favoriteResult = favoriteMapper.selectOne(Wrappers.lambdaQuery(Favorite.class)
                .eq(Favorite::getUserId, uid)
                .eq(Favorite::getObjectId, favoriteParam.getObjectId()));

        // 判断是否已经收藏过这篇文章
        if (favoriteResult != null) {
            // 已经收藏过，需要将收藏的记录删除掉
            int deleted = favoriteMapper.delete(Wrappers.lambdaQuery(Favorite.class)
                    .eq(Favorite::getUserId, uid)
                    .eq(Favorite::getObjectId, favoriteParam.getObjectId()));
            return deleted > 0;
        }

        // 没有收藏过，则进行收藏操作，就是根据用户id、文章id、收藏对象类型进行插入操作
        Favorite favorite = new Favorite();
        favorite.setUserId(uid);
        favorite.setObjectId(favoriteParam.getObjectId());
        favorite.setObjectType(favoriteParam.getObjectType());

        // 向收藏表插入数据
        int result = favoriteMapper.insert(favorite);

        return result > 0;

    }
}
